package com.zhj.controller;

import com.zhj.entities.CommonResult;
import com.zhj.entities.Payment;
import com.zhj.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 张红娟
 * @Date: 2021/9/15 13:53
 * @Version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/save")
    public CommonResult save(@RequestBody Payment payment) {
        int result = paymentService.save(payment);
        log.info("-----插入结果：" + result);
        if (result > 0) {
            return new CommonResult(200,"插入成功！serverPort:" + serverPort);
        } else {
            return new CommonResult(444,"插入失败！请重试...");
        }
    }

    @GetMapping(value = "/getPaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("-----查询结果：" + payment);
        if (payment != null) {
            return new CommonResult(200,"查询成功！serverPort:" + serverPort,payment);
        } else {
            return new CommonResult(444,"没有对应记录,查询id为：" + id,null);
        }
    }

    // 服务发现Discovery
    @GetMapping(value = "/discovery")
    public Object discovery() {

        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("----- " + service);
        }

        List<ServiceInstance> discoveryClientInstances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance discoveryClientInstance : discoveryClientInstances) {
            log.info(discoveryClientInstance.getServiceId() + "\t" +
                    discoveryClientInstance.getHost() + "\t" +
                    discoveryClientInstance.getPort() + "\t" +
                    discoveryClientInstance.getUri());
        }
        return this.discoveryClient;
    }

    // 手写负载均衡算法
    @GetMapping(value = "/lb")
    public String getPaymentLB() {
        return serverPort;//返回服务接口
    }

    @GetMapping("/feign/paymentFeignTimeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
